<?php

namespace App\Http\Controllers\NonPublicVersion;

use App\Http\Controllers\Common;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ErrorCode;
use App\Http\Controllers\SuccessCode;
use App\Http\Requests\GameRequest;
use App\Model\GameList as Model;
use App\Model\GamePackage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Http\Controllers\Curl;
use DB;

class GameList extends Controller
{
    use Common;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //DB::enableQueryLog();
        $app_name = $request->get('app_name','');
        $platform = $request->get('platform','');

        $pageSize = $request->get('paginate',config('web.page.num'));

        $where = [];
        if ($platform > 0) {
            $where[] = ['platform', $platform];
        }
        if ($app_name) {
            $where[] = ['app_name', 'like', "%{$app_name}%"];
        }
        $lists = DB::table('game_list')->select('game_list.*','game_config.app_name')
            ->leftJoin('game_config', 'game_config.game_id', '=', 'game_list.game_id')
            ->where($where)
            ->paginate($pageSize);

        /*$lists = Model::with(['gameConfig'=>function ($query) use($app_name){
            $query->where('app_name', 'like', "%{$app_name}%");
        }])->where($where)->paginate($pageSize);*/
        //dd($lists);
        //echo $lists[0]->gameConfig->app_name;
//dd($lists);
        $query = [
            'app_name' => $app_name,
            'platform' => $platform,
        ];
        //dump(DB::getQueryLog());

//
//        if ($keywords || $platform){
//            $lists = $this->remoteQuery('appLib/sdk_search_app',[
//                'keywords' => $keywords,
//                'platform' => $platform,
//                'page' => $page,
//                'pagesize' => $pageSize
//            ]);
//        } else {
//            $lists = $this->remoteQuery('appLib/app_list',[
//                'page' => $page,
//                'pagesize' => $pageSize
//            ]);
//        }
//
//        $supplier = $this->remoteQuery('appLib/get_supplier_list');
//
//        $arr = config('web.platform');
//
//        if (!empty($lists['data'])){
//            foreach ($lists['data'] as $key => $list) {
//                $fileName = Model::where('game_id',$list['app_id'])->first(['package_path','note','id']);
//                $channelPackageNum = GamePackage::where('game_id',$list['app_id'])->count();
//                $lists['data'][$key]['filename'] = $fileName ?  $fileName->package_path : '';
//                $lists['data'][$key]['id'] = $fileName ?  $fileName->id : '';
//                $lists['data'][$key]['note'] = $fileName ?  $fileName->note : '';
//                $lists['data'][$key]['channelPackageNum'] = $channelPackageNum;
//                $lists['data'][$key]['platform'] = $arr[$list['platform']];
//            }
//
//            $lists['totalPage'] = ceil($lists['total'] / $pageSize);
//        } else {
//            $lists['totalPage'] = 1;
//        }
//        $lists['url'] = url('/nonPublicVersion/game');


        return view('nonPublicVersion.game.index', [
            'lists' => $lists,
            'suppliers' => [],
//            'pageSize' => $pageSize,
            'query' => $query
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //$supplier = $this->remoteQuery('appLib/get_supplier_list');
        return view('nonPublicVersion.game.add',[
          //  'supplier' => $supplier
        ]);
    }

    public function getSupplier()
    {
        $supplier = $this->remoteQuery('appLib/get_supplier_list');
        return $this->getView($supplier,SuccessCode::GET_SUCCESS);
    }

    public function uploadFile(Request $request)
    {
        if ($request->hasFile('package') && $request->file('package')->isValid()) {
            $file = $request->file('package');
            $ext = $file->getClientOriginalExtension();
            if (!in_array($ext, config('web.upload.apk'))) {
                return $this->getView([], ErrorCode::UPLOAD_TYPE_ERROR);
            }
            $name = $file->getClientOriginalName();
            $path = $file->storeAs(config('web.upload.apk_upload_dir'), $name);
            return $this->getView(['path' => $path], SuccessCode::UPLOAD_SUCCESS);
        } else {
            return $this->getView([],ErrorCode::UPLOAD_ERROR);
        }
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(GameRequest $request)
    {
        $data = $request->all();
        $game = Model::where('game_id', $data['game_id'])->first();
        //dd($game);
        if (isset($game)) {
            return $this->getView([], ErrorCode::GAME_LIST_EXIST);
        }
        $post = Model::create($data);
        $id = $post->getAttribute('id');

        if ($id) {
            return $this->getView(['id' => $data['game_id']], SuccessCode::ADD_SUCCESS);
        } else {
            return $this->getView([], ErrorCode::ADD_ERROR);
        }
    }

    /**
     * 编辑 文件查看下载
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $collect = Model::where('game_id',$id)->first();
        if ($collect && file_exists(base_path( 'storage/app/' .$collect->package_path)))
        {
            return response()->download(realpath(base_path( 'storage/app/' .$collect->package_path)));
        }
    }
    /**
     * 添加 文件查看下载
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function down(Request $request)
    {
        $package_path = $request->get('package_path','');
        $id = $request->get('id',0);
        if (file_exists(base_path( 'storage/app/' .$package_path)))
        {
            return response()->download(realpath(base_path( 'storage/app/' .$package_path)));
        }
        if($id){
            $collect = Model::where('game_id',$id)->first();
            if ($collect && file_exists(base_path( 'storage/app/' .$collect->package_path)))
            {
                return response()->download(realpath(base_path( 'storage/app/' .$collect->package_path)));
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //echo 1111;exit;
        $oldData = $this->remoteQuery('appLib/get_app_by_ids',[
            'app_ids' => $id,
        ]);

        $oldData = current($oldData);

        $collect = Model::where('game_id',$id)->first();
        $oldData['package_path'] = $collect ? $collect->package_path : '';
        $oldData['note'] = $collect ? $collect->note : '';

        $oldData['platform'] = config('web.platform')[$oldData['platform']];
        return view('nonPublicVersion.game.edit',[
            'oldData' => $oldData
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(GameRequest $request, $id)
    {
        $path = $request->input('package_path', '');
        $note = $request->input('note', '');
        $is_update = $request->input('is_update',0);
        $data = $request->all();
        $arr = [
            'package_path' => $path,
        ];
        $arr['note'] = $note;
        //如果有就修改,没有就增加
        $check = Model::where('game_id',$id)->first();
        if ($check){
            $res = Model::where('game_id',$id)->update($arr);
            if($is_update){
                $result = Curl::query([ 
                    'url' => config('web.game_update_query'), 
                    'isPost' => false, 
                    'dataStr' =>[
                        'game_id' => $id,
                    ],
                ]);
            }
        } else {
            $note = $request->input('note', '');
            $arr = [
                'package_path' => $path,
                'note' => $note,
                'game_id' => $id,
            ];
            $res = Model::insertGetId($arr);
        }

        if ($res !== false) {
            return $this->getView([], SuccessCode::EDIT_SUCCESS);
        } else {
            return $this->getView([], ErrorCode::EDIT_ERROR);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,$id)
    {
        $ids = $request->get('ids','');
        if ($ids){
            Model::whereIn('id',explode(',',$ids))->delete();
        } else {
            Model::find($id)->delete();
        }
        return $this->getView([],SuccessCode::DEL_SUCCESS);
    }

    /**
     * 大文件分片上传
     */
    public function uploadchunk(Request $request)
    {
        // 唯一ID
        $guid = $request->input('guid');
        // 分片序号
        $chunk = $request->input('chunk', 0);
        // 总分片数
        $chunks =  $request->input('chunks');
        // 分片保存名称
        $chunkName = (string) ($chunk + 100000);

        $file = $request->file('file');
        $ext = $file->getClientOriginalExtension();

        if ($ext != 'apk'){
            return $this->getView([],ErrorCode::GAME_UPLOAD_EXIST);
        }

        $name = $file->getClientOriginalName();
//        $name = Str::random(40) . '.' .$ext;

        $storagePath =  config('web.upload.apk_upload_dir') . '/tmp/';

        $path = $file->storeAs($storagePath,$chunkName. '.tmp');

        // 最后一个分片,或者文件太小没有分片
        if ($chunks == 0 || $chunks == $chunk + 1) {
            $data = $this->_mergeChunk($storagePath,$name);
            if ($data) {
                $path = $data['path'];
                return $this->getView($path,SuccessCode::ADD_SUCCESS);
            }
        } else {
            return $this->getView([],SuccessCode::UPLOAD_SUCCESS);
        }
    }
    /**
     * 合并文件
     * @param $info
     * @return array|bool
     */
    private function _mergeChunk($storagePath,$oldName)
    {
        $tmpDir =  storage_path('app/'.$storagePath);
        if (is_dir($tmpDir)) {
            // 文件目录
            $saveDir = dirname($tmpDir);

            // 保存文件路径
            $savePath = $saveDir. '/' . $oldName;

            // 遍历临时目录所有文件
            $files = array_diff(scandir($tmpDir), array('.', '..'));

            $image = '';
            // 创建保存文件
            file_put_contents($savePath, $image);
            // 修改app文件权限
            // 排序升序
            sort($files);
            foreach ($files as $file) {
                $image = file_get_contents($tmpDir. $file);
                file_put_contents($savePath, $image, FILE_APPEND);
                // 删除文件
                unlink($tmpDir. $file);
            }
            // 删除临时目录
            rmdir($tmpDir);
            // 保存文件
            $data = array(
                'type' => '',
                'md5'  => md5_file($savePath),
                'ext'  => '',
                'size' => filesize($savePath),
                'name' => $oldName,
                'path' => dirname($storagePath) . '/' . $oldName,
            );
            return $data;
        }

        return false;
    }
}
